var express = require('express');
var router = express.Router();
var moment = require('moment');
var fs = require('fs');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

moment.locale('zh-cn');

function getRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
}

var pad = function(tbl) {
    return function(num, n){
        n = n - (''+num).length;
        // console.log('asdasd=='+n);
        return (0 >= n) ? num : (tbl[n] || (tbl[n] = Array(n + 1).join(0)))+num;
    }    
}([]);

function pip_build_process(req, res, fileKey) {
    var fn = (function (error, stdout, stderr) {
        var msg = '';
        if (error !== null) {
            msg = '调用执行命令时发生错误: <br/>' + (error + '').replace(/\n/g, '<br/>\n');
        } else if (stderr.length > 0) {
            msg = '调用执行命令时发生错误: <br/>' + (stderr + '').replace(/\n/g, '<br/>\n');
        } else {
            msg = '<br/>'+
                stdout.replace(/\n/g, '<br/>\n') + '<br/><br/>'+
                '<a href="/download?id=' + fileKey + '">下载结果文件</a>';
        }
        res.render('upload', { title: 'PIP依赖提取工具', filekey: fileKey, message: msg });
    });
    return fn;
}

//单个依赖提取服务
router.post('/executecmd', function (req, res, next) {
    var cmd = req.body.cmd;

    if (cmd && cmd.length > 0) {
        console.log('收到一个请求：' + cmd);

        var formatDate = moment().format('YYYYMMDDHHmmss'); /*格式化时间*/
        var randNum = getRandomNum(0, 999999);
        var fileKey = formatDate + '_' + pad(randNum, 6);
        // console.log('[DEBUG]==fileKey: ' + fileKey);

        (function(req, res, fileKey){
            // 执行命令
            var cmdStr = './bin/pip_build 3 ' + cmd + ' ' + fileKey;
            // console.log('[DEBUG]==CMD: ' + cmd);
            exec(cmdStr, pip_build_process(req, res, fileKey));
        })(req, res, fileKey);
    } else {
        res.send('执行失败');
    }
});

router.process_async = function(req, callback, callback_err) {
    var cmd = req.body.cmd;

    if (!cmd || cmd.length == 0) {
        return;
    }

    if (cmd == 'hello') {
        const welcomeStr = '================================================================================\n'+
            '欢迎使用WEB命令行！\n'+
            '注意事项：\n'+
            '会在一个临时目录中执行所有命令，执行后会将当前目录的所有内容打包转入内网并尝试提交到仓库。\n'+
            '支持分号隔开的多句命令执行。请不要使用ping、read等可能导致终端卡住的命令。\n'+
            '================================================================================\n'+
            '[END]\n';
        callback(welcomeStr);
        return;
    }

    console.log('收到一个请求：' + cmd);

    var formatDate = moment().format('YYYYMMDDHHmmss'); /*格式化时间*/
    var randNum = getRandomNum(0, 999999);
    var fileKey = formatDate + '_' + pad(randNum, 6);
    // console.log('[DEBUG]==fileKey: ' + fileKey);
    var timeout = 0;
    if (cmd.startsWith('ping ')) {
        timeout = 10 * 1000;
        callback('ping命令限制运行不超过10秒！\n');
    }

    var child = spawn('/bin/bash', [
        '-c', cmd
    ], {
        cwd: '/tmp',
        env: process.env,
        timeout: timeout
    });

    child.stdout.on('data', callback);
    child.stderr.on('data', callback_err);
};

module.exports = router;
